<!-- 验证插件 -->
<script src="/static/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="/static/plugins/jquery-validation/localization/messages_zh.min.js"></script>
<!-- 针对当前主题进行简单封装，精简代码 -->
<script src="/static/sdtheme/scripts/sdvalidate.js"></script>

<script src="/static/plugins/typeahead/js/bootstrap3-typeahead.js"></script>

<script>
    var index = parent.layer.getFrameIndex(window.name);
    var $input = $('#typeahead');

    $(function () {
        pageInit()
    });

    function pageInit() {
        loadDataList();
        validateInfo();
    }
    
    function loadDataList() {
        $.ajax({
            url: '{{urlfor "CourseContentController.ItemData"}}',
            dataType: 'json',
            success: function (res) {
                if (res.code === 0) {
                    console.log(res.obj);
                    $input.typeahead({
                        source: res.obj,
                        autoSelect: true
                    });
                    $input.change(function () {
                        var current = $input.typeahead("getActive");
                        if (current) {
                            if (current.name === $input.val()) {
                                $('#CourseContentId').val(current.id)
                            }
                        }
                    })
                }
            }
        });
    }

    function validateInfo() {
        var $thisForm = $('#thisForm');
        $thisForm.sdvalidate({
            rules: {
                typeahead: {
                    required: true
                }
            },
            submitHandler: function (form) {
                var url = '{{urlfor "CourseContentController.Match"}}';
                var params = $thisForm.serialize();
                $.sdpost(url, params, function (res) {
                    if (res.code === 0) {
                        parent.layer.msg(res.msg)
                        parent.refresh(res.obj)
                        parent.layer.close(index)
                    } else {
                        parent.layer.alert(res.msg, {icon: 2, title: '失败'})
                    }
                });
                return false
            }
        });
    }

    function FormSubmit() {
        $('#thisForm').submit();
    }
</script>